class Solution
{
public:
    vector<int> findOrder(int n, vector<vector<int>>& prerequisites)
    {
        unordered_map<int, vector<int>> edges;
        vector<int> in(n);

        for (auto& e : prerequisites)
        {
            int a = e[0], b = e[1];
            edges[b].push_back(a);
            in[a]++;
        }

        queue<int> q;
        vector<int> ret;

        for (int i = 0; i < n; i++)
        {
            if (in[i] == 0)
                q.push(i);
        }
        while (q.size())
        {
            int t = q.front();
            q.pop();
            ret.push_back(t);

            for (int a : edges[t])
            {
                in[a]--;
                if (in[a] == 0)
                    q.push(a);
            }
        }
        if (ret.size() == n) return ret;
        else return {};
    }
};